package dian.qing.li.demo.security.controller;

import com.pactera.redis.utils.RedisUtils;
import dian.qing.li.demo.security.commons.RestResult;
import dian.qing.li.demo.security.constants.Constants;
import dian.qing.li.demo.security.constants.RedisKey;
import dian.qing.li.demo.security.utils.Assert;
import dian.qing.li.demo.security.utils.JwtUtils;
import dian.qing.li.demo.security.utils.VerifyCodeUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证
 *
 * @author: liqingdian
 **/
@RestController
@RequestMapping(name = "认证", value = "/v1/auth")
public class AuthController {

    @GetMapping(name = "获取验证码", value = "/verify-code")
    public RestResult verifyCode(HttpServletResponse response) {
        //设置页面不缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        //设置输出的内容的类型为JPEG图像
        response.setContentType("image/jpeg");
        // 生成验证码
        String verifyCode = VerifyCodeUtils.generateTextCode(VerifyCodeUtils.TYPE_NUM_ONLY, 4, null);
        // 生成缓存标识
        String uniquekey = VerifyCodeUtils.generateTextCode(VerifyCodeUtils.TYPE_ALL_MIXED, 32, null);
        response.setHeader(Constants.VERIFY_CODE_HEADER, uniquekey);
        // 生成图片
        String imgUrl = VerifyCodeUtils.defaultImgUrl(verifyCode);
        Map<String, Object> data = new HashMap<>();
        data.put(Constants.VERIFY_CODE_HEADER, uniquekey);
        data.put(Constants.VERIFY_CODE_IMAGE, imgUrl);
        // 添加缓存
        String redisKey = RedisUtils.redisKey(RedisKey.VERIFY_CODE, uniquekey);
        RedisUtils.put(redisKey, verifyCode, 120);
        return RestResult.succeed(data);
    }

    @PatchMapping(name = "刷新TOKEN", value = "/token-refresh")
    public RestResult refreshToken(HttpServletRequest request, HttpServletResponse response) {
        String token = JwtUtils.getJwtToken(request);
        Assert.isNotBlank(token, "Authorization: Bearer不能为空");
        JwtUtils.cancel(request);
        token = JwtUtils.refreshToken(token, Constants.JWT_SECRET);
        JwtUtils.refresh(token);
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        response.setHeader("Authorization", token);
        return RestResult.succeed(data);
    }
}
